<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JAVA异常处理 | 后端学习记录</title><meta name="keywords" content="Java"><meta name="author" content="h0ss"><meta name="copyright" content="h0ss"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、异常分类异常对象均派生于Throwable类，而Throwable又分解为Error和Exception两个分支，其中Error应该在代码层面避免，而不是作异常处理。 设计程序时一般只关注Exception类下的异常，这下面包含两个异常子类，一个是RuntimeException，另一个是IOException。 1、RuntimeException一般来说，RuntimeException属">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA异常处理">
<meta property="og:url" content="https://blog.gpnusz.cn/2021/02/02/JAVA%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="后端学习记录">
<meta property="og:description" content="一、异常分类异常对象均派生于Throwable类，而Throwable又分解为Error和Exception两个分支，其中Error应该在代码层面避免，而不是作异常处理。 设计程序时一般只关注Exception类下的异常，这下面包含两个异常子类，一个是RuntimeException，另一个是IOException。 1、RuntimeException一般来说，RuntimeException属">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tse2-mm.cn.bing.net/th/id/OIP.anGjOGF_UjPBdekSgF-wnQAAAA?pid=ImgDet&rs=1">
<meta property="article:published_time" content="2021-02-02T06:09:22.000Z">
<meta property="article:modified_time" content="2022-08-20T18:17:50.071Z">
<meta property="article:author" content="h0ss">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tse2-mm.cn.bing.net/th/id/OIP.anGjOGF_UjPBdekSgF-wnQAAAA?pid=ImgDet&rs=1"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://blog.gpnusz.cn/2021/02/02/JAVA%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2022-08-21 02:17:50'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">51</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">后端学习记录</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">JAVA异常处理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-02T06:09:22.000Z" title="发表于 2021-02-02 14:09:22">2021-02-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-08-20T18:17:50.071Z" title="更新于 2022-08-21 02:17:50">2022-08-21</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span></div></div></div><article class="post-content" id="article-container"><h3 id="一、异常分类"><a href="#一、异常分类" class="headerlink" title="一、异常分类"></a>一、异常分类</h3><p>异常对象均派生于Throwable类，而Throwable又分解为Error和Exception两个分支，其中Error应该在代码层面避免，而不是作异常处理。</p>
<p>设计程序时一般只关注Exception类下的异常，这下面包含两个异常子类，一个是RuntimeException，另一个是IOException。</p>
<h4 id="1、RuntimeException"><a href="#1、RuntimeException" class="headerlink" title="1、RuntimeException"></a>1、RuntimeException</h4><p>一般来说，RuntimeException属于编程错误造成的异常，包括数组越界、空指针等等，这类异常与Error类下的异常统称为非检查型异常。</p>
<h4 id="2、IOException"><a href="#2、IOException" class="headerlink" title="2、IOException"></a>2、IOException</h4><p>IOException属于非编程错误造成的异常，例如试图超越文件尾部读取数据、打开一个不存在的文件等等。这类异常称为检查型异常，程序员要为检查型异常提供异常处理器。</p>
<h4 id="3、自定义异常类"><a href="#3、自定义异常类" class="headerlink" title="3、自定义异常类"></a>3、自定义异常类</h4><p>有时需要抛出不包括在标准异常类中的异常，就需要定义一个派生于Exception（或其子类）的类，用来满足需求。</p>
<p>自定义异常类通常需要有两个构造器，一个无参，一个带详细信息参数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 自定义异常类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExceptionSelf</span> <span class="keyword">extends</span> <span class="title">Exception</span></span>&#123;</span><br><span class="line">    <span class="comment">// 无参构造器</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ExceptionSelf</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">    <span class="comment">// 带详细描述信息参数的构造器</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ExceptionSelf</span><span class="params">(String msg)</span></span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="二、异常处理"><a href="#二、异常处理" class="headerlink" title="二、异常处理"></a>二、异常处理</h3><h4 id="1、声明异常与抛出异常"><a href="#1、声明异常与抛出异常" class="headerlink" title="1、声明异常与抛出异常"></a>1、声明异常与抛出异常</h4><p>1）<strong>在方法首部声明这个方法可能抛出的异常，用的是throws关键字，这将把异常抛给上一级处理</strong>。如果一个方法可能出现的异常不止一种，那么就需要用逗号分隔不同的异常全部列举出来。同时，也不允许声明非检查型的异常，即从Error类或者RuntimeException类继承的异常。</p>
<p>这里需要注意的是，如果超类方法没有声明任何检查型异常，那么子类方法也不能声明。</p>
<p>2）也可以在可能出错的地方<strong>主动抛出一个异常对象，用的是throw关键字</strong>，如果这里没有对异常进行捕获处理，那么同样需要在方法头部声明该异常。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.EOFException;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExceptionDemo</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getName</span><span class="params">()</span> <span class="keyword">throws</span> EOFException</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> EOFException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3）<strong>throw throws的区别</strong></p>
<p>throw是抛出一个异常类对象，在代码中去抛出，一般格式为throw new xx()</p>
<p>而throws是抛出异常给上一级去作处理，在方法首部去声明，这里只是抛出异常类名，一般格式为：throws xxx </p>
<h4 id="2、捕获异常"><a href="#2、捕获异常" class="headerlink" title="2、捕获异常"></a>2、捕获异常</h4><p><strong>1）try…catch…finally</strong></p>
<p>把可能出现异常的地方放在try代码块内，在后面接上catch处理对应的异常，一个try可以有多个catch子句（不能存在子类关系）用于捕获不同的异常。如果try中的语句出现异常，那么将跳过剩下的try代码，直接执行catch语句内容，如果带有finally子句，将在catch代码执行完毕后执行，一般用于IO设备的关闭等操作，注意不要把控制流的语句放在里面。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        <span class="comment">// 这是可能出现异常的代码块</span></span><br><span class="line">        <span class="keyword">int</span> sum = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span>(Exception err)&#123;</span><br><span class="line">        <span class="comment">// 对对应异常进行处理</span></span><br><span class="line">        System.out.println(err.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 一般执行关闭流的操作</span></span><br><span class="line">        System.out.println(<span class="string">&quot;do the close operate&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在工具类中一般不适用这种方法，而是将异常throws给调用者去做对应的处理。更加合适的操作是：在catch子句中对异常类型进行转换，将原始异常设置为新异常的原因，然后再throw抛给调用者。</p>
<p><strong>2）try-with-resource</strong></p>
<p>这就出现一个问题，如果在finally语句的关闭操作也出现异常，那还需要进行再一次的异常处理，于是有了try-with-resource这种捕获异常的方法，与python的with xxx as xxx 操作同理。在try代码块运行结束之后，资源会被自动关闭，而对于这种操作也可以有catch和finally子句，这些子句会在资源关闭后执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">    <span class="comment">// 把需要打开的流资源写在try后的括号中</span></span><br><span class="line">    <span class="keyword">try</span>(<span class="keyword">var</span> in = <span class="keyword">new</span> Scanner(<span class="keyword">new</span> FileInputStream(<span class="string">&quot;I:/javastudy/demo.txt&quot;</span>), StandardCharsets.UTF_8))&#123;</span><br><span class="line">        <span class="keyword">while</span>(in.hasNext())&#123;</span><br><span class="line">            System.out.println(in.next());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 作异常处理 此时流资源已关闭</span></span><br><span class="line">    <span class="keyword">catch</span> (Exception err)&#123;</span><br><span class="line">        System.out.println(err.getMessage());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 无需使用finally子句进行资源关闭</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="三、断言"><a href="#三、断言" class="headerlink" title="三、断言"></a>三、断言</h3><p>1、断言是jdk1.4后引入的内容，用关键字assert来表示。如果在程序中需要检测一个参数是否合法，一般是使用if语句来操作，但是测试完毕这部分代码依旧会存于程序中，这时候就需要引入assert断言，断言不是程序的一部分，在测试完毕之后移除该代码，程序仍不会收到影响。（注：idea默认断言是关闭的，需要加上 -ea 运行参数启动）</p>
<p>2、断言语法格式为：<strong>assert condition : expression(可省略)</strong></p>
<p>如果condition不成立，程序将运行expression然后终止运行并抛出一个AssertionError。如果condition成立，程序正常运行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> sum = <span class="number">6</span>;</span><br><span class="line">    <span class="keyword">assert</span> sum==<span class="number">5</span> : <span class="string">&quot;sum不等于5&quot;</span>;</span><br><span class="line">    System.out.println(<span class="string">&quot;---如果断言正常---&quot;</span>);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>3、断言失败是致命的，不可恢复的，不应使用断言与用户进行沟通，应该只用于内部调试测试过程。</p>
<h3 id="四、日志"><a href="#四、日志" class="headerlink" title="四、日志"></a>四、日志</h3><p><strong>1、日志框架</strong></p>
<p>1）<strong>Log4j 或 Log4j 2</strong> —— Apache的开源项目，通过使用Log4j，我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等；用户也可以控制每一条日志的输出格式；通过定义每一条日志信息的级别，用户能够更加细致地控制日志的生成过程。这些可以通过一个配置文件（XML或Properties文件）来灵活地进行配置，而不需要修改程序代码。Log4j 2则是前任的一个升级，参考了Logback的许多特性；<br>2）<strong>Logback</strong>—— Logback是由log4j创始人设计的又一个开源日记组件。logback当前分成三个模块：logback-core,logback- classic和logback-access。logback-core是其它两个模块的基础模块。logback-classic是log4j的一个改良版本。此外logback-classic完整实现SLF4J API使你可以很方便地更换成其它日记系统如log4j或JDK14 Logging；<br>3）<strong>java.util.logging</strong> —— JDK内置的日志接口和实现，功能比较简；<br>4）<strong>Slf4j</strong> —— SLF4J是为各种Logging API提供一个简单统一的接口），从而使用户能够在部署的时候配置自己希望的Logging API实现；<br>5）<strong>Apache Commons Logging</strong> —— Apache Commons Logging （JCL）希望解决的问题和Slf4j类似。</p>
<p>为了避免引入依赖的繁琐性，这里用java内部的日志框架来记录各项操作。</p>
<p>2、日志使用</p>
<p>1）基本日志使用：要生成简单的日志可使用全局日志记录器并调用info方法。使用这种方法日志将会直接打印在控制台。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.logging.*;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ExceptionSelf</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">        <span class="comment">// 关闭所有级别日志输出</span></span><br><span class="line">        Logger.getGlobal().setLevel(Level.OFF);</span><br><span class="line">        <span class="comment">// 开启所有级别日志输出</span></span><br><span class="line">        Logger.getGlobal().setLevel(Level.ALL);</span><br><span class="line">        <span class="comment">// 输出一条info级别的日志信息在控制台</span></span><br><span class="line">        Logger.getGlobal().info(<span class="string">&quot;这是一条测试日志信息&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>2）高级日志使用：可以自定义日志记录器，而不是全部记录在全局记录器中，而且用静态变量存储日志存记录器的引用可以避免垃圾误回收。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这里的日志记录器名最好定义为当前类的类名 xx.class.getName()</span></span><br><span class="line"><span class="comment">// 并且日志记录器一般定义之后不会再改变，所以存储它的引用的变量应为final类型</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger Log = Logger.getLogger(ExceptionSelf.class.getName());</span><br></pre></td></tr></table></figure>

<p>日志级别如下，一般默认情况下只会记录INFO以上的日志，也可以手动调节显示级别。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">SEVERE</span><br><span class="line">WARNING</span><br><span class="line">INFO</span><br><span class="line">CONFIG</span><br><span class="line">FINE</span><br><span class="line">FINER</span><br><span class="line">FINEST</span><br><span class="line"><span class="comment">// 可以进行级别调整</span></span><br><span class="line">Log.setLevel(Level.WARNING);</span><br></pre></td></tr></table></figure>

<p>3）注意点</p>
<p>a、在一个对象中通常只使用一个Logger对象，Logger应该是static final的，只有在少数需要在构造函数中传递logger的情况下才使用private final。<br>b、输出Exceptions的全部Throwable信息，因为logger.error(msg)和logger.error(msg,e.getMessage())这样的日志输出方法会丢失掉最重要的StackTrace信息。<br>c、不允许记录日志后又抛出异常，因为这样会多次记录日志，只允许记录一次日志。<br>d、不允许出现System print(包括System.out.println和System.error.println)语句。<br>e、不允许出现printStackTrace。<br>f、日志性能的考虑，如果代码为核心代码，执行频率非常高，则输出日志建议增加判断，尤其是低级别的输出&lt;debug、info、warn&gt;。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">h0ss</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://blog.gpnusz.cn/2021/02/02/JAVA%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/">https://blog.gpnusz.cn/2021/02/02/JAVA%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://blog.gpnusz.cn" target="_blank">后端学习记录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/2021/02/02/String%E4%B8%89%E5%85%84%E5%BC%9F/"><img class="prev-cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">String三兄弟</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/11/16/给开源项目提了个PR/" title="给开源项目提了个PR"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-16</div><div class="title">给开源项目提了个PR</div></div></a></div><div><a href="/2022/08/21/【Debug】bitField-引发的栈溢出排错记/" title="【Debug】bitField 引发的栈溢出排错记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-21</div><div class="title">【Debug】bitField 引发的栈溢出排错记</div></div></a></div><div><a href="/2022/07/16/【RPC】详解SPI机制/" title="【RPC】详解SPI机制"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-16</div><div class="title">【RPC】详解SPI机制</div></div></a></div><div><a href="/2022/07/10/【RPC】基本网络通信模型/" title="【RPC】基本网络通信模型"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">【RPC】基本网络通信模型</div></div></a></div><div><a href="/2022/07/02/【JVM】类加载全过程简记/" title="【JVM】类加载全过程简记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-02</div><div class="title">【JVM】类加载全过程简记</div></div></a></div><div><a href="/2022/06/28/【RPC】RPC实战与核心的学习笔记/" title="【RPC】RPC实战与核心的学习笔记"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-28</div><div class="title">【RPC】RPC实战与核心的学习笔记</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">h0ss</div><div class="author-info__description">一个苦逼后端仔的学习记录</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">51</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/h0ss"><i class="fab fa-github"></i><span>Gitee仓库</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">Java后端技术栈语雀文档：https://www.yuque.com/oliver-wdtb1/java</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/" title="给开源项目提了个PR">给开源项目提了个PR</a><time datetime="2022-11-15T17:28:40.000Z" title="发表于 2022-11-16 01:28:40">2022-11-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/09/03/%E3%80%90MySQL%E3%80%91InnoDB%E7%9A%84%E8%A1%8C%E6%A0%BC%E5%BC%8F/" title="【MySQL】InnoDB的行格式">【MySQL】InnoDB的行格式</a><time datetime="2022-09-02T18:17:38.000Z" title="发表于 2022-09-03 02:17:38">2022-09-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/08/21/%E3%80%90Debug%E3%80%91bitField-%E5%BC%95%E5%8F%91%E7%9A%84%E6%A0%88%E6%BA%A2%E5%87%BA%E6%8E%92%E9%94%99%E8%AE%B0/" title="【Debug】bitField 引发的栈溢出排错记">【Debug】bitField 引发的栈溢出排错记</a><time datetime="2022-08-20T18:10:40.000Z" title="发表于 2022-08-21 02:10:40">2022-08-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/07/16/%E3%80%90RPC%E3%80%91%E8%AF%A6%E8%A7%A3SPI%E6%9C%BA%E5%88%B6/" title="【RPC】详解SPI机制">【RPC】详解SPI机制</a><time datetime="2022-07-15T18:51:57.000Z" title="发表于 2022-07-16 02:51:57">2022-07-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/07/14/%E3%80%90Redis%E3%80%91%E9%87%8D%E8%A6%81%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%9F%BA%E7%A1%80/" title="【Redis】重要数据结构基础">【Redis】重要数据结构基础</a><time datetime="2022-07-13T17:22:08.000Z" title="发表于 2022-07-14 01:22:08">2022-07-14</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="爱国,敬业,诚信,友善,自由,平等,公正,法治,富强,民主,文明,和谐" data-fontsize="16px" data-random="false" async="async"></script></div></body></html>